package com.sx.zongzhi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.MultiImageAdapter;
import com.sx.zongzhi.bean.BoxSearchBean;
import com.sx.zongzhi.bean.ContactBean;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.presenter.AddMailPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.FileUtils;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.CommentView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.AudioDialog;
import com.sx.zongzhi.widget.LoadDialog;
import com.zero.smallvideorecord.MediaRecorderActivity;
import com.zero.smallvideorecord.model.MediaRecorderConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 添加消息
 */
public class AddMailActivity extends BaseActivity implements View.OnClickListener, CommentView, UploadFileView {

//    @BindView(R.id.gridView)
//    NoScrollGridView gridView;
    @BindView(R.id.et_Title)
    EditText et_Title;
    @BindView(R.id.et_Content)
    EditText et_Content;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    @BindView(R.id.tv_Add)
    TextView tvAdd;
    @BindView(R.id.ll_person_gv)
    LinearLayout llPersonGv;
    private MultiImageAdapter adapter;
//    private InObjectAdapter objectAdapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    private PopupWindow selectPop;
//    private List<String> persons = new ArrayList<>();
    private List<ContactBean> contactBeanLists = new ArrayList<>();

    private String userIds = "", groupIds = "", orgIds = "";
    private String title = "", content = "";
    private  AudioDialog audioDialog;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_mail);
        setTitleName("消息新增");
        setTitleRight(R.string.submit);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        adapter.setOnItemClickListener(new MultiImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position, View v) {
                String type = selectList.get(position).getSuffixType();
                String path = selectList.get(position).getPath();
                if (".mp4".equalsIgnoreCase(type)) {
                    startActivity(new Intent(AddMailActivity.this, VideoPlayerActivity.class).putExtra(
                            "path",path));
                } else if (".amr".equalsIgnoreCase(type)) {
                    if (audioDialog!=null){
                        audioDialog.startPlay(path);
                    }
                } else {
                    startActivity(new Intent(AddMailActivity.this, ImagePlayActivity.class).putExtra(
                            "path", path));
                }
            }
        });
//        objectAdapter = new InObjectAdapter(this, R.layout.item_text_delete, persons);
//        gridView.setAdapter(objectAdapter);
    }

    @OnClick({R.id.tv_right, R.id.tv_Add})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                getRecives();
                if (BaseUtil.isEmpty(userIds) && BaseUtil.isEmpty(groupIds) && BaseUtil.isEmpty(orgIds)) {
                    ToastUtils.showToast(AddMailActivity.this, "请输入接收对象");
                    return;
                }
                title = et_Title.getText().toString().trim();
                if (BaseUtil.isEmpty(title)){
                    et_Title.setError( "请输入标题");
                    return;
                }
                if (title.length() > 25){
                    et_Title.setError( "标题长度不可大于25");
                    return;
                }
                content = et_Content.getText().toString().trim();
                if (BaseUtil.isEmpty(content) && selectList.size() == 0){
                    ToastUtils.showToast(AddMailActivity.this,"请输入内容，或上传附件");
                    return;
                }
                if (content.length() > 1000){
                    et_Content.setError( "内容长度不可大于1000");
                    return;
                }
                LoadDialog.show(AddMailActivity.this, "发送中...");
                if (selectList.size() > 0){
                    List<File> files = new ArrayList<>();
                    for (PhotoBean localMedia : selectList) {
                        files.add(new File(localMedia.getPath()));
                    }
                    new UploadFilePest(this).uploadFile(this, files);
                }else {
                    new AddMailPest(this).addBoxDetail(this, content, title, "", userIds, groupIds, orgIds);
                }

                break;
            case R.id.tv_Add:
                startActivityForResult(new Intent(this, SelectPersonActivity.class).putExtra("contactBean", selectContactBean), 1);
                break;
        }
    }

    private void getRecives() {
        if (selectContactBean == null){
            ToastUtils.showToast(AddMailActivity.this,"请输入接收对象");
            return;
        }
        userIds = "";
        groupIds = "";
        orgIds = "";
        List<ContactBean> contactList = selectContactBean.contactBeanList;
        if (contactList != null && contactList.size() > 0) {
            for (ContactBean contactBean : contactList) {
                userIds += contactBean.id + ",";
            }
        }
        if (!BaseUtil.isEmpty(userIds)) {
            userIds = userIds.substring(0, userIds.length() - 1);
        }

        List<ContactBean> contactGroupList = selectContactBean.contactGroupsBeanList;
        if (contactGroupList != null && contactGroupList.size() > 0) {
            for (ContactBean contactBean : contactGroupList) {
                groupIds += contactBean.id + ",";
            }
        }
        if (!BaseUtil.isEmpty(groupIds)) {
            groupIds = groupIds.substring(0, groupIds.length() - 1);
        }

        List<ContactBean> contactOrgList = selectContactBean.contactOrgBeanList;
        if (contactOrgList != null && contactOrgList.size() > 0) {
            for (ContactBean contactBean1 : contactOrgList) {
                orgIds += contactBean1.id + ",";
            }
        }
        if (!BaseUtil.isEmpty(orgIds)) {
            orgIds = orgIds.substring(0, orgIds.length() - 1);
        }
    }

    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                showPopupSelect();
            } else {
                ToastUtils.showToast(AddMailActivity.this, "最多上传三项");
            }
        }
    };


    /**
     * 显示选择文件的弹窗
     */
    private void showPopupSelect() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_file, null);
        if (selectPop == null) {
            selectPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            selectPop.setTouchable(true);
            selectPop.setOutsideTouchable(false);
            selectPop.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
        }
        view.findViewById(R.id.tv_Picture).setOnClickListener(this);
        view.findViewById(R.id.tv_File).setOnClickListener(this);
        view.findViewById(R.id.tv_Audio).setOnClickListener(this);
        view.findViewById(R.id.tv_Video).setOnClickListener(this);
        view.findViewById(R.id.tv_Cancel).setOnClickListener(this);
        selectPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_Picture:
                int max = 3 - selectList.size();
                if (max > 0) {
                    PictureSelector.create(this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.MULTIPLE)
                            .maxSelectNum(max)// 最大图片选择数量 int
//                            .previewImage(true)// 是否可预览图片
//                            .enableCrop(true)
                            .compress(true)
                            .compressGrade(Luban.CUSTOM_GEAR)
                            .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                } else {
                    ToastUtils.showToast(AddMailActivity.this, "最多上传三项");
                }
                break;
            case R.id.tv_File://选文件
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                try {
                    startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), 4447);
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(this, "Please install a File Manager.",  Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_Audio:
                if (audioDialog==null){
                    audioDialog=new AudioDialog(AddMailActivity.this);
                    audioDialog.setCancelable(false);
                    audioDialog.getAudioBack(new AudioDialog.AudioCallback() {
                        @Override
                        public void getData(String filePath, int countdown) {
                            PhotoBean photoBean = new PhotoBean(filePath, ".amr");
                            selectList.add(photoBean);
                            if (adapter != null) adapter.notifyDataSetChanged();
                        }
                    });
                }
                audioDialog.show(audioDialog.AUDIO_RECODERD);
                break;
            case R.id.tv_Video:
                MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                        .smallVideoWidth(640)
                        .smallVideoHeight(480)
                        .recordTimeMax(10 * 1000)
                        .maxFrameRate(20)
                        .minFrameRate(8)
                        .captureThumbnailsTime(1)
                        .videoBitrate(580000)
                        .build();
                MediaRecorderActivity.goSmallVideoRecorder(this, DisputeAddActivity.class.getName(), config);
                break;
            case R.id.tv_Cancel:
                break;
        }
        selectPop.dismiss();
    }

    private ContactBean selectContactBean;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                initIds((ContactBean) data.getSerializableExtra("contactBean"));
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                if (!picUrls.isEmpty()) {
                    for (LocalMedia localMedia : picUrls) {
                        String path = localMedia.getCompressPath();
                        String type = path.substring(path.lastIndexOf("."));
                        selectList.add(new PhotoBean(path, type));
                    }
                    if (adapter != null) adapter.notifyDataSetChanged();
                }
            }else if (requestCode == MediaRecorderActivity.FOR_RESULT){
                String videoUri = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                if (!TextUtils.isEmpty(videoUri)) {
                    String type = videoUri.substring(videoUri.lastIndexOf("."));
                    selectList.add(new PhotoBean(videoUri, type));
                    if (adapter != null) adapter.notifyDataSetChanged();
                }
            }else if (requestCode == 4447){
                Uri selectedMediaUri = data.getData();
                String path = FileUtils.getPath(this, selectedMediaUri);
                if (!BaseUtil.isEmpty(path)) {
                    String type = path.substring(path.lastIndexOf("."));
                    if (".txt".equalsIgnoreCase(type)||".docx".equalsIgnoreCase(type)||".doc".equalsIgnoreCase(type)
                            ||".pdf".equalsIgnoreCase(type)||".xls".equalsIgnoreCase(type)){

                        selectList.add(new PhotoBean(path, type));
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showToast(this,"不支持当前类型文件上传");
                    }
                }else {
                    ToastUtils.showToast(this,"文件异常请重新选择");
                }
            }
        }
    }

    private void initIds(ContactBean contactBeans) {
        contactBeanLists.clear();
        if (selectContactBean == null){
            selectContactBean = new ContactBean();
            selectContactBean.contactBeanList = new ArrayList<>();
            selectContactBean.contactGroupsBeanList = new ArrayList<>();
            selectContactBean.contactOrgBeanList = new ArrayList<>();
        }
        List<ContactBean> contactList = contactBeans.contactBeanList;
        if (contactList.size() > 0) {
            contactBeanLists.addAll(contactList);
            selectContactBean.contactBeanList.clear();
            for (ContactBean contactBean : contactList) {
                contactBean.selectType = 1;
                selectContactBean.contactBeanList.add(contactBean);
            }
        }
        List<ContactBean> contactGroupList = contactBeans.contactGroupsBeanList;
        if (contactGroupList.size() > 0) {
            contactBeanLists.addAll(contactGroupList);
            selectContactBean.contactGroupsBeanList.clear();
            for (ContactBean contactBean : contactGroupList) {
                contactBean.selectType = 2;
                selectContactBean.contactGroupsBeanList.add(contactBean);
            }
        }
        List<ContactBean> contactOrgList = contactBeans.contactOrgBeanList;
        if (contactOrgList.size() > 0) {
            contactBeanLists.addAll(contactOrgList);
            selectContactBean.contactOrgBeanList.clear();
            for (ContactBean contactBean : contactOrgList) {
                contactBean.selectType = 3;
                selectContactBean.contactOrgBeanList.add(contactBean);
            }
        }
        llPersonGv.removeAllViews();
        llPersonGv.addView(GetChangeableView());
    }

    private View GetChangeableView() {
        LinearLayout ParentLayout = new LinearLayout(AddMailActivity.this);
        ParentLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout linearLayout = new LinearLayout(AddMailActivity.this);
        float allwidth = 0;
        float eachWidth = 0;
        int screenWidth = BaseUtil.getScreenWidth(AddMailActivity.this) - BaseUtil.dp2px(AddMailActivity.this,20);
        int idx = 0;
        if (contactBeanLists != null){
            for (final ContactBean contactBean : contactBeanLists) {
                FrameLayout itemView = (FrameLayout) LayoutInflater.from(AddMailActivity.this).inflate(R.layout.item_text_delete,null);
                final TextView textView=(TextView) itemView.findViewById(R.id.tv_Name);
                final ImageView imageView = (ImageView) itemView.findViewById(R.id.imv_Delete);
                textView.setTextSize(15);
                textView.setText(contactBean.getName());
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        contactBeanLists.remove(contactBean);
                        if (contactBean.selectType == 1){
                            selectContactBean.contactBeanList.remove(contactBean);
                        }else if (contactBean.selectType == 2){
                            selectContactBean.contactGroupsBeanList.remove(contactBean);
                        }else {
                            selectContactBean.contactOrgBeanList.remove(contactBean);
                        }
                        llPersonGv.removeAllViews();
                        llPersonGv.addView(GetChangeableView());
                    }
                });
                eachWidth = GetAllTextViewWidth(textView) + textView.getPaddingLeft()
                        + textView.getPaddingRight() + textView.getScaleX()*(contactBean.getName().length()-1)
                        +((FrameLayout.LayoutParams)textView.getLayoutParams()).leftMargin
                        + ((FrameLayout.LayoutParams)textView.getLayoutParams()).rightMargin;
//                        + imageView.getPaddingRight() + imageView.getWidth();
                allwidth = allwidth + eachWidth;

                if(screenWidth >= allwidth){
                    linearLayout.addView(itemView);
                    eachWidth=0;
                }else{
                    ParentLayout.addView(linearLayout);
                    linearLayout = new LinearLayout(AddMailActivity.this);
                    linearLayout.addView(itemView);
                    allwidth = eachWidth;
                    eachWidth=0;
                }

                idx++;
                if(contactBeanLists.size() == idx){
                    ParentLayout.addView(linearLayout);
                }
            }
        }
        return ParentLayout;
    }

    /**获取textview总长度*/
    private float GetAllTextViewWidth(TextView tv){
        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        tv.measure(spec, spec);
        // textView getPaint measureText
        TextPaint textPaint = tv.getPaint();
        float textPaintWidth = textPaint.measureText(tv.getText().toString());
        return textPaintWidth;
    }

    @Override
    public void commentSuccess(Boolean result) {
        LoadDialog.dismiss(AddMailActivity.this);
        BoxSearchBean boxSearchBean = new BoxSearchBean();
        boxSearchBean.mailType = 1;
        MyRxBus.get().post(boxSearchBean);
        finish();
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(AddMailActivity.this);
        ToastUtils.showToast(AddMailActivity.this, message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        String picUrls = "";
        for (PhotoBean bean : beans) {
            picUrls += bean.getPath() + ",";
        }
        picUrls.substring(0, picUrls.length() - 1);
        new AddMailPest(this).addBoxDetail(this, content, title, picUrls.toString(), userIds, groupIds, orgIds);
    }
}
